package org.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.entity.Books;
import org.service.BooksService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

//这个pageController控制器专门用于分页完成
@Controller
@RequestMapping(value = "/page")
public class PageController {
    @Resource
    private BooksService booksService;
    //显示首页
    @RequestMapping(value = "/pagelist")
    public String bookpage(Model model) throws JsonProcessingException {
        //通过service获得分页的list信息
        ObjectMapper mapper = new ObjectMapper();

        List<Books> booksList = booksService.queryAllByLimit(0, 3);
        model.addAttribute("bookslist",booksList);
        return "booklist";
    }
    //显示上一页或下一页，使用ajax获取值
    @RequestMapping(value = "/changePage")
    public void changePage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //通过service获得分页的list信息
        String pagecount = request.getParameter("pagecount");
        System.out.println("pagecount:"+pagecount);
        ObjectMapper mapper = new ObjectMapper();

        List<Books> booksList = booksService.queryAllByLimit((Integer.parseInt(pagecount)-1)*3, 3);
        //将获取的list信息转化为json字符串
        String bookslistjson = mapper.writeValueAsString(booksList);
        //使用response来设置json提交的数据中文解析，json数据需要进行额外处理，model处理不需要这样
       //默认的json是使用iso-8859-1，需要进行response端转化
        //不能依赖于控制器的过滤器的字符编码处理，需要手动添加json的客户端中文字符处理
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        System.out.println(bookslistjson);
        //将当前的页数存储起来
        request.setAttribute("pagecount",pagecount);
        //ajax前端获取返回的list的json字符串
        out.println(bookslistjson);
    }
}
